<template>
  <div>
    <!--面包屑区域    -->

    <div class="breadcrumb-box">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :key="item.name+''+index" v-for="(item,index) in breadcrumb"
                            :to="{ path: item.toPath?item.toPath:'' }"
        >
          {{ item.name }}
          {{ this.templateId }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    {{breadcrumb}}
    <!-- 内容卡片区域 搜索栏 用户列表 -->
    <el-card class="box-card">
      <commentHeader
          :name="template.title">
        <template v-slot:buttons>
          <!--头部按钮 -->
          <CustomCommButton
              :buttonClick="systemButton"
              location="top"
              button-key="operationType"
              :buttons="template.buttons"></CustomCommButton>
        </template>
      </commentHeader>
      <div class="search-box">
        <div class="search-item-box" :key="item.key" v-for="(item) in getSearchFields">
          <span>{{ item.title }}</span>
          <el-input
              v-model="item.searchValue"
              clearable>
          </el-input>
        </div>
        <el-button @click="searchTableData" type="primary">搜索</el-button>
      </div>
      <el-table
          :data="template.tableListData"
          height="500"
          border
          empty-text="加载中"
          class="user-list-table"
          @select="rowCheckboxSelectEvent"
          @select-all="allRowCheckboxSelectEvent"
      >
        <el-table-column
            type="selection"
            align="center"
            width="55">
        </el-table-column>

        <el-table-column v-for="(item,index) in template.displayColumns"
                         :key="index+item.key"
                         :prop="item.key"
                         :label="item.title"
                         :align="item.align"
                         class="user-list-table-column"
                         :style="{'max-width':item.tableWidth}"
        >
<!--          {{item}}-->
          <template v-if="item.type ==='img' ||item.type ==='imgs'" v-slot="scope">
            <img v-if="item.type ==='img'" class="table-item-img" :src="'/api/source/'+scope.row[item.key]">
          </template>
        </el-table-column>

        <el-table-column label="操作"
                         align="center"
                         :v-if="false"
        >

          <template #default="scope">
            <CustomCommButton
                :buttonClick="systemButton"
                :scope="scope"
                location="action"
                button-key="operationType"
                :buttons="template.buttons"></CustomCommButton>
          </template>
        </el-table-column>
      </el-table>
      <!--
      size-change和current-change事件来处理页码大小和当前页变动时候触发的事件
           -->

      <div class="pagination-box">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="countSize">
        </el-pagination>
      </div>
    </el-card>
    <!--  弹出层  -->
    <el-dialog
        width="1000px"
        v-if="dialog"
        v-model="dialog">
      <commentForm
          ref="commentForm"
          :functionType="functionType"
          :scope="scope"
          :customClose="formClose"
          :fromTemplateId="fromTemplateId"
      >
      </commentForm>
    </el-dialog>
  </div>

</template>

<script>
import {
  findById, listFilter, selectCustomCondition, getKeyList
  , customInterface, setTableSearch,
  mDeleteByIds, mDeleteById
} from '@/components/request/publicApi'

export default {
  name: "CustomCommTable",
  props: {
    templateIdTag:{
      type:Boolean,
      default:()=>{
        return false;
      }
    },
    /*面包屑配置*/
    breadcrumb: {
      type: Array,
      default: () => {
        return [
          {
            'name': '名称',
            'toPath': '面包屑的点击跳转页面（非必须）'
          }
        ];
      },
      required: true
    },
    /*表格头部配置*/
    tableHeard: {
      type: Object,
      default: () => {
        return {
          /*       title: "请求头标题",
                 buttons: [
                   {
                     /!*按钮功能类型 from（表单） operation（操作接口）*!/
                     functionType: "from",
                     /!*表单配置关联字段*!/
                     fromConfig: {},
                     /!*操作接口的类型 （）*!/
                     operationType: "",
                     /!*操作接口的访问接口*!/
                     operationPort: "",
                     /!*请求接口的参数 搜索框的 search ，表格选择的 tableList*!/
                     portPara: {
                       search: {},
                       tableList: {}
                     },
                     name: "添加配置",
                     key: "12",
                     icon: "",
                     /!*primary success info warning danger*!/
                     type: "primary",
                     show: false,
                   }, {
                     /!*按钮功能类型 from（表单） operation（操作接口）*!/
                     functionType: "from",
                     /!*表单配置关联字段*!/
                     fromConfig: {},
                     /!*操作接口的类型 （）*!/
                     operationType: "",
                     /!*操作接口的访问接口*!/
                     operationPort: "",
                     /!*请求接口的参数 搜索框的 search ，表格选择的 tableList*!/
                     portPara: {
                       search: {},
                       tableList: {}
                     },
                     name: "删除",
                     key: "12",
                     icon: "",
                     /!*primary success info warning danger*!/
                     type: "warning",
                     show: false,
                   }]*/
        }
      }
    },
    /*表格头部字段配置*/
    tableHeardFieldsList: {
      type: Array,
      required: false,
      /*
      [
        {
          "prop": "username",
          "label": "姓名",
          "width": "180"
        }
      ]
      */
    },
    /*表格数据*/
    tableListData: [],
  },
  data() {
    return {
      scope: {},
      functionType: "",
      showDialog: false,
      templateId: "",
      /*模板对象*/
      template: {
        // tableListData: [
        //   {
        //     "phone": "saada",
        //     "id": 6,
        //     "pwd": "65a5373f09d8e458ddd7a256b931da03",
        //     "email": "adsa",
        //     "username": "s21"
        //   },
        //   {
        //     "phone": "w",
        //     "id": 940309940814217216,
        //     "pwd": "ade668dfa0d496f5bdc2716e99c860ac",
        //     "email": "wwwww",
        //     "username": "qw"
        //   },
        //   {
        //     "phone": "qqq",
        //     "id": 940309904466378752,
        //     "pwd": "d3c90b8d2420b7aada7d6c0c3310bef9",
        //     "email": "qqq",
        //     "username": "wqw"
        //   },
        //   {
        //     "phone": "122",
        //     "id": 940299005248667648,
        //     "pwd": "8c4d5cad3fc90e5f13535bd5f615282d",
        //     "email": "2222",
        //     "username": "张三"
        //   }
        // ]
      },
      /*操作栏按钮判断*/
      actionButtonShow: false,
      /*弹出层控制字段*/
      dialog: false,
      /**/
      fromList: [],
      fromConfig: {},
      fromTemplateId: "",
      fromButton: [],
      dialogKey: "12",
      /*分页参数*/
      page: 1,
      pageSize: 10,
      countSize: 0,
      /*复选框id集合*/
      checkBoxIds: [],

    }
  },
  mounted() {
    console.log('mounted')

  },
  /**
   * 数据对象 data 已存在，可以调用 methods 中的方法，操作 data 中的数据，但 dom 未生成，$el 未存在 。
   */
  created() {
    // this.templateId = this.$route.query;
    this.init();
  },
  provide() {
    return {
      fClearDialog: this.clearDialog,
      // parDisplay: this.parDisplay,
    };
  },
  /*计算属性*/
  computed: {
    getButtons() {
      return listFilter(this.template.buttons, 'action');
    },
    getSearchFields() {
      return listFilter(this.template.result_columns, true, 'isBaseSearch');
    }

  },
  methods: {
    /*
   页码大小变动时候触发的事件
    * */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.searchTableData();
    },
    /*
    当前页变动时候触发的事件
    * */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.searchTableData();
    },
    /*行点击触发事件*/
    rowCheckboxSelectEvent(selection, row) {
      this.checkBoxIds = [];
      selection.forEach((item) => {
        this.checkBoxIds.push(item.id)
      })
    },
    /*选择所有行点击触发事件*/
    allRowCheckboxSelectEvent(selection, row) {
      this.checkBoxIds = [];
      selection.forEach((item) => {
        this.checkBoxIds.push(item.id)
      })
    },
    // formClose
    formClose() {
      this.dialog = false;
      this.searchTableData();
    },
    clearDialog() {
      this.showDialog = false;
    },
    /**
     * 按钮操作
     * 字段：functionType{ addFrom,showFrom, updateFrom,del,req}
     * 两个:{
     *   打开表单
     *   请求接口
     * }
     */
    systemButton(data, scope) {
      let functionType = data['functionType'];
      if ('add' === functionType) {
        this.dialog = true;
        this.showDialog = true;
        this.functionType = functionType;
        // console.log('按钮操作',data,this.dialog)
        //获取添加表单按钮配置
        // let addFromPar = {
        //   "source": "A_TEMPLATE",
        //   "_id": data.templateId,
        // };
        this.fromTemplateId = data.templateId;
      } else if ('update' === functionType) {
        this.functionType = functionType
        this.fromTemplateId = data.templateId;
        this.scope = scope;
        this.dialog = true;
      } else if ('del' === functionType) {
        if (!this.checkBoxIds || this.checkBoxIds.length === 0) {
          this.$message.error("没有选择数据")
        } else {
          getKeyList(this.checkBoxIds, "id")
        }
        //删除数据的条件
        let delQuery = {
          ids: this.checkBoxIds,
        };
        mDeleteByIds(this.template.source, delQuery).then((res) => {
          this.searchTableData();
        }).catch(() => {
          this.searchTableData();
        })

      }
    },
    searchTableData() {

      let dataPar = {
        restFields: getKeyList(this.template.result_columns, "key"),
        page: this.page,
        pageSize: this.pageSize,
      };
      dataPar = setTableSearch(dataPar, this.template);
      if (!this.template.customInterface === 'default') {

        customInterface(this.template.customInterface, dataPar).then((res) => {
          //设置数据
          this.template.tableListData = res.data.data;

          this.countSize = res.data.countSize;
          this.checkBoxIds = [];
        }).catch((error) => {
          this.$message.error("操作失败")
        })
      } else {

        //获取表格的初始数据
        selectCustomCondition(this.template.source, dataPar)
            .then((res) => {
              //设置数据
              this.template.tableListData = res.data.data;
              this.countSize = res.data.countSize;
              this.checkBoxIds = [];
            }).catch((error) => {
          this.$message.error("操作失败")
        })

      }

    },
    /*初始化操作*/
    async init() {
      // const urlParams = new URLSearchParams(window.location.search);
      // this.templateId = urlParams.get('templateId');
      if(this.templateIdTag==false){
        this.templateId  = window.localStorage.getItem("sys_template")
      }

      let par = {
        "_id": this.templateId,
        "source": "A_TEMPLATE"
      }
      await findById(par).then((res) => {
        //获取系统模板数据
        this.template = res.data.data;
        this.pageSize = this.template.config.pageSize
        console.log('初始化', this.template)
        /*查询表格数据*/
        this.searchTableData();
      }).catch((error) => {
        // console.log(error)
      })
    },
    /*是否有操作按钮的权限*/
    whetherNeedOperation() {
      console.log('whetherNeedOperation', typeof this.template.buttons)
      let actionArray = listFilter(this.template.buttons, 'action');
      return actionArray.length === 0;
    }
  }
}
</script>

<style lang="less" scoped>
.demo-pagination-block {
  margin-top: 10px;
}

.box-card {
  margin-top: 20px;
  //position: relative;

  .heard-box {
    display: flex;
    //border: 1px solid red;
    border-bottom: 1px solid red;
    justify-content: space-between;
    align-items: center;
    height: 50px;

    .label-box {
      display: flex;
    }

    .button-box {
      display: flex;
    }
  }

  .search-box {
    //position: relative;

    margin-top: 20px;
    //border: 1px solid red;
    width: 100%;
    box-sizing: border-box;
    /**/
    //display: block;
    .input-item {
      display: inline-block;
      //display: flex;
      align-items: center;
      height: 40px;

    }

    .el-input {
      width: 200px;
      margin-left: 10px;
      //margin-top: 10px;
    }

    .el-button {
      margin-left: 10px;
      //margin-top: 10px;
    }
  }

  /*分页盒子*/

  .pagination-box {
    margin-top: 20px;
  }
}

.search-box {
  margin-top: 20px;
  width: 100%;
  box-sizing: border-box;

  .search-item-box {
    display: inline-block;
    align-items: center;
    height: 40px;
    margin-left: 10px;
  }

  .input-item {
    display: inline-block;
    align-items: center;
    height: 40px;
  }

  .el-input {
    width: 200px;
    margin-left: 10px;
  }

  .el-button {
    margin-left: 10px;
  }
}

.user-list-table {
  position: relative;

  margin-top: 20px;
  width: 100%;
  height: 100%;

  .user-list-table-column {
    border: 1px solid #000;
    border-right: none;
    border-bottom: none;
  }
}
.table-item-img{
  height: 25px;
}

</style>
